import { Component, OnInit } from '@angular/core';
import { EChartOption } from 'echarts';
import { DataVisualizationService } from '../dataVisualization.service';
import { TranslateService } from '@ngx-translate/core';
import { PublicService } from 'app/public/public.service';
import { SELECT_OPTIONS } from 'app/app.constants';
import { ToolsService } from 'app/shared/service';

@Component({
    selector: 'itmp-incident-analytics',
    templateUrl: './incident-analytics.component.html',
    styleUrls: ['./incident-analytics.component.css']
})
export class IncidentAnalyticsComponent implements OnInit {
    category_options_last: EChartOption;
    category_options_this: EChartOption;
    zone_options: EChartOption;
    pattern_options: EChartOption;
    month_options: EChartOption;
    type_options_last: EChartOption;
    type_options_this: EChartOption;
    reason_options_last: EChartOption;
    reason_options_this: EChartOption;
    category_data_last: any;
    category_data_this: any;
    zone_data: any;
    pattern_data: any;
    month_data: any;
    type_data_last: any;
    type_data_this: any;
    reason_data_last: any;
    reason_data_this: any;
    reasonObj = {};

    constructor(
        private ds: DataVisualizationService,
        private translate: TranslateService,
        private pub: PublicService,
        private toolService: ToolsService
    ) {}

    ngOnInit() {
        this.getReasonList();
        this._getData();
        this.translate.onLangChange.subscribe(() => this._getData());
    }

    getReasonList() {
        const res = this.pub.getSelectOptionsList(SELECT_OPTIONS.CAUSE_TYPE);
        console.log(res, '结果~~~~~~~');

        (res.data || []).forEach(item => {
            this.reasonObj[item.value] = {
                name: this.toolService.getCapitalLetters(item.name),
                vietName: this.toolService.getCapitalLetters(item.vietName)
            };
        });
    }

    // Statics(by Incident Category)
    _getCategory(data) {
        this.category_data_this = [];
        this.category_data_last = [];
        let eventTotal = 'eventTotal';
        let noEventTotal = 'noEventTotal';
        this.translate.get('Data_Visualization.IncidentAnalytics.eventTotal').subscribe((res: string) => {
            eventTotal = res || '';
        });
        this.translate.get('Data_Visualization.IncidentAnalytics.noEventTotal').subscribe((res: string) => {
            noEventTotal = res || '';
        });
        setTimeout(() => {
            data.forEach(category => {
                const arr = [
                    { value: category['eventTotal'], name: eventTotal },
                    {
                        value: category['noEventTotal'],
                        name: noEventTotal
                    }
                ];
                if (category.nameType === 'thisyear') {
                    this.category_data_this = arr;
                } else if (category.nameType === 'lastyear') {
                    this.category_data_last = arr;
                }
            });
            this._setCategoryOptions();
        });
    }

    // Statics(by Zone)
    _getZone(data) {
        this.zone_data = [];
        data.forEach(item => {
            if (item.nameType === 'lastYear') {
                this.zone_data.push({
                    product: item.ZONE_ID,
                    'Last year': item.total,
                    'This year': 0
                });
            } else if (item.nameType === 'thisYear') {
                let has = false;
                this.zone_data.forEach(it => {
                    if (it.product === item.ZONE_ID) {
                        it['This year'] = item.total;
                        has = true;
                        return;
                    }
                });
                if (!has) {
                    this.zone_data.push({
                        product: item.ZONE_ID,
                        'Last year': 0,
                        'This year': item.total
                    });
                }
            }
        });
        this._setZoneOptions();
    }

    _getMonth(data) {
        this.month_data = {
            lastYear: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            thisYear: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            baseLine: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]
        };
        data.forEach(item => {
            if (item.nameType === 'thisYear') {
                this.month_data.thisYear[item.Month - 1] = +item.total;
            } else if (item.nameType === 'lastYear') {
                this.month_data.lastYear[item.Month - 1] = +item.total;
            }
        });
        this._setMonthOptions();
    }

    getReasonName(reason) {
        let lang = localStorage.getItem('itmp_lang');
        if (lang == 'en') {
            return (this.reasonObj[reason] && this.reasonObj[reason].name) || reason;
        } else {
            return (this.reasonObj[reason] && this.reasonObj[reason].vietName) || reason;
        }
    }

    // Statics(by Incident Reason)
    _getReason(data) {
        this.reason_data_this = [];
        this.reason_data_last = [];
        data.forEach(item => {
            switch (item.nameType) {
                case 'thisYear':
                    this.reason_data_this.push({
                        value: +item.total,
                        name: this.getReasonName(item.reason)
                    });
                    break;
                case 'lastYear':
                    this.reason_data_last.push({
                        value: +item.total,
                        name: this.getReasonName(item.reason)
                    });
                    break;
            }
            //     if (item.nameType === 'thisYear') {
            //         this.reason_data_this.push({
            //             value: +item.total,
            //             name: item.reason
            //         });
            //         this.reason_data_last.push({
            //             value: 0,
            //             name: item.reason
            //         });
            //     } else {
            //         let has = false;
            //         this.reason_data_last.forEach(el => {
            //             if (el.name === item.reason) {
            //                 el.value = +item.total;
            //                 has = true;
            //                 return;
            //             }
            //         });
            //         if (!has) {
            //             this.reason_data_this.push({
            //                 value: 0,
            //                 name: item.reason
            //             });
            //             this.reason_data_last.push({
            //                 value: +item.total,
            //                 name: item.reason
            //             });
            //         }
            //     }
        });
        this._setReasonOptions();
    }

    // Statics(by Incident Pattern)
    _getPattern(data) {
        const pattern = [];
        data.forEach(item => {
            let has = false;
            pattern.forEach(it => {
                if (item.PatternType === it.product) {
                    if (item.nameType === 'thisYear') {
                        it['This year'] = +item.total;
                    } else if (item.nameType === 'lastYear') {
                        it['Last year'] = +item.total;
                    }
                    has = true;
                    return;
                }
            });
            if (!has) {
                if (item.nameType === 'thisYear') {
                    pattern.push({ product: item.PatternType, 'Last year': 0, 'This year': +item.total });
                } else if (item.nameType === 'lastYear') {
                    pattern.push({ product: item.PatternType, 'Last year': +item.total, 'This year': 0 });
                }
            }
        });
        this.pattern_data = pattern;
        this._setPatternOptions();
    }

    // Statics(by Incident Type)
    _getType(data) {
        this.type_data_this = [];
        this.type_data_last = [];
        data.forEach(item => {
            switch (item.nameType) {
                case 'thisYear':
                    this.type_data_this.push({
                        value: +item.total,
                        name: item.PatternType
                    });
                    break;
                case 'lastYear':
                    this.type_data_last.push({
                        value: +item.total,
                        name: item.PatternType
                    });
                    break;
            }
            // if (item.nameType === 'thisYear') {
            //     this.type_data_this.push({
            //         value: +item.total,
            //         name: item.PatternType
            //     });
            //     this.type_data_last.push({
            //         value: 0,
            //         name: item.PatternType
            //     });
            // } else if (item.nameType === 'lastYear') {
            //     let has = false;
            //     this.type_data_last.forEach(el => {
            //         if (el.name === item.PatternType) {
            //             el.value = +item.total;
            //             has = true;
            //             return;
            //         }
            //     });
            //     if (!has) {
            //         this.type_data_this.push({
            //             value: 0,
            //             name: item.PatternType
            //         });
            //         this.type_data_last.push({
            //             value: +item.total,
            //             name: item.PatternType
            //         });
            //     }
            // }
        });
        this._setTypeOptions();
    }

    // 获取数据
    _getData() {
        this.ds.getIncidentAnalyticsReport(202).subscribe(res => {
            if (res.messagecode === '000000') {
                const category_data = res.data.filter(cur => cur.selectedType === 'category' && cur.nameType);
                this._getCategory(category_data);
                const zone_data = res.data.filter(cur => cur.selectedType === 'zone');
                this._getZone(zone_data);
                const month_data = res.data.filter(cur => cur.selectedType === 'month');
                this._getMonth(month_data);
                const reason_data = res.data.filter(cur => cur.selectedType === 'reason');
                this._getReason(reason_data);
                const pattern_data = res.data.filter(cur => cur.selectedType === 'Pattern');
                this._getPattern(pattern_data);
                const type_data = res.data.filter(cur => cur.selectedType === 'type');
                this._getType(type_data);
            }
        });
    }

    /* Statistics(by Incident Category) */
    _setCategoryOptions() {
        function commonOptions(data, showLegend: boolean, seriesOptions) {
            return {
                backgroundColor: '#363a70', //背景色
                legend: {
                    show: showLegend,
                    orient: 'vertical',
                    right: 0,
                    top: 0,
                    textStyle: {
                        color: '#ffffff' //图例颜色
                    }
                    // itemGap: 10
                },

                xAxis: {
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0,0,0,0)' //轴线颜色
                        }
                    }
                },
                yAxis: {
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(0,0,0,0)' //轴线颜色
                        }
                    }
                },
                tooltip: {
                    formatter: '{b}: {c} / {d}%'
                },
                color: ['#FDD158', '#71B5F4', '#62ACEB', '#B3D465', '#F39800', '#6C6CFF'],
                series: [
                    {
                        name: 'This Year',
                        type: 'pie',
                        radius: ['25%', '60%'],
                        center: ['50%', '60%'],
                        data,

                        label: {
                            formatter: params => {
                                if (params.percent >= 5) {
                                    return `${params.percent}%`;
                                } else {
                                    return '';
                                }
                            }
                            // rotate: true
                        },
                        labelLine: {
                            show: false,
                            length: 5,
                            length2: 5
                        },
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        ...seriesOptions
                    },
                    {
                        type: 'pie',
                        radius: ['25%', '35%'],
                        center: ['50%', '60%'],
                        hoverAnimation: false,
                        data: [1],
                        itemStyle: {
                            //修改图例的颜色
                            color: '#61a0a9'
                        },
                        labelLine: {
                            show: false
                        },
                        tooltip: {
                            show: false
                        },
                        ...seriesOptions
                    }
                ]
            };
        }

        this.category_options_last = commonOptions(this.category_data_last, false, { name: 'Last Year' }) as EChartOption;
        this.category_options_this = commonOptions(this.category_data_this, true, {
            name: 'This Year',
            center: ['35%', '60%']
        }) as EChartOption;
    }

    /* Statistics(by Zone) */
    _setZoneOptions() {
        const tempTranslate = [{ title: 'product' }, { title: 'Last_year' }, { title: 'This_year' }];
        tempTranslate.forEach(item => {
            this.translate.get('Data_Visualization.IncidentAnalytics.' + item.title).subscribe((res: string) => {
                item.title = res || '';
            });
        });
        this.zone_data.forEach(item => {
            this.translate.get('Data_Visualization.IncidentAnalytics.' + item.product).subscribe((res: string) => {
                item.product = res || '';
            });
        });
        setTimeout(() => {
            this.zone_data.forEach(item => {
                (item[tempTranslate[0].title] = item.product),
                    (item[tempTranslate[1].title] = item['Last year']),
                    (item[tempTranslate[2].title] = item['This year']);
            });
            this.zone_options = {
                backgroundColor: '#363a70', //背景色
                legend: {
                    right: 50,
                    textStyle: {
                        color: '#ffffff'
                    }
                },
                tooltip: {},
                dataset: {
                    dimensions: [tempTranslate[0].title, tempTranslate[1].title, tempTranslate[2].title],
                    source: this.zone_data
                },

                xAxis: {
                    type: 'category',
                    boundaryGap: true,
                    // axisLabel: {
                    //     interval: 0
                    // }
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#fff', //左边线的颜色
                            width: '1' //坐标线的宽度
                        }
                    }
                },
                yAxis: {
                    splitNumber: 4 /* 将纵坐标分成几段 */,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#fff', //左边线的颜色
                            width: '1' //坐标线的宽度
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'inside'
                    }
                ],
                series: [
                    {
                        itemStyle: { color: '#238CE6' },
                        type: 'bar',
                        barMaxWidth: 20
                    }
                    // {
                    //     itemStyle: { color: '#FDD158' },
                    //     type: 'bar',
                    //     barMaxWidth: 20
                    // }
                ]
            };
        });
    }

    /* Statistics(by Incident Pattern) */
    _setPatternOptions() {
        const tempTranslate = [{ title: 'product' }, { title: 'Last_year' }, { title: 'This_year' }];
        tempTranslate.forEach(item => {
            this.translate.get('Data_Visualization.IncidentAnalytics.' + item.title).subscribe((res: string) => {
                item.title = res || '';
            });
        });
        this.pattern_data.forEach(pattern => {
            if (pattern.product === 'Vehicle on fire') {
                if (localStorage.getItem('itmp_lang') === 'vi') {
                    pattern.product = 'Xe cháy';
                } else {
                    pattern.product = 'Vehicle On Fire';
                }
            }
        });
        setTimeout(() => {
            this.pattern_data.forEach(item => {
                (item[tempTranslate[0].title] = item.product),
                    (item[tempTranslate[1].title] = item['Last year']),
                    (item[tempTranslate[2].title] = item['This year']);
            });

            this.pattern_options = {
                backgroundColor: '#363a70', //背景色
                legend: {
                    right: 50,
                    textStyle: {
                        color: '#ffffff'
                    }
                },
                tooltip: {},
                dataset: {
                    dimensions: [tempTranslate[0].title, tempTranslate[1].title, tempTranslate[2].title],
                    source: this.pattern_data
                },
                xAxis: {
                    type: 'category',
                    axisLabel: {
                        interval: 0,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#fff', //左边线的颜色
                            width: '1' //坐标线的宽度
                        }
                    }
                },
                yAxis: {
                    splitNumber: 4,
                    /* 将纵坐标分成几段 */
                    // max: 120,
                    // min: 0
                    axisLabel: {
                        interval: 0,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#fff', //左边线的颜色
                            width: '1' //坐标线的宽度
                        }
                    }
                },
                series: [
                    {
                        itemStyle: { color: '#238CE6' },
                        type: 'bar',
                        barWidth: 20
                    }
                    // {
                    //     itemStyle: { color: '#FDD158' },
                    //     type: 'bar',
                    //     barWidth: 20
                    // }
                ]
            };
        });
    }
    // 44
    /* Statistics(by Month) */
    _setMonthOptions() {
        const tempLegend = ['Last_year', 'This_year', 'Base_Line'];
        // const tempLegend = ['Last year', 'This year', 'Base Line'];
        const legend = [];
        const tempData = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        const tempTranslete = [];
        tempLegend.forEach(item => {
            this.translate.get('Data_Visualization.Overall.' + item).subscribe((res: string) => {
                legend.push(res);
            });
        });
        tempData.forEach(item => {
            this.translate.get('Data_Visualization.Overall.' + item).subscribe((res: string) => {
                tempTranslete.push(res);
            });
        });
        setTimeout(() => {
            this.month_options = {
                backgroundColor: '#363a70', //背景色
                legend: {
                    data: legend,
                    textStyle: {
                        color: '#ffffff'
                    },
                    right: 20,
                    top: 0
                },
                tooltip: {
                    trigger: 'axis'
                },
                xAxis: {
                    // axisLabel: {

                    // },
                    type: 'category',
                    splitNumber: 12,
                    data: tempTranslete,
                    axisLabel: {
                        interval: 0,
                        show: true,
                        rotate: 30,
                        textStyle: {
                            //x轴座标文字颜色
                            color: '#fff',
                            fontSize: 10
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#fff', //左边线的颜色
                            width: '1' //坐标线的宽度
                        }
                    }
                },
                yAxis: {
                    type: 'value',
                    splitNumber: 4,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            //轴座标文字颜色
                            color: '#fff'
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#fff', //左边线的颜色
                            width: '1' //坐标线的宽度
                        }
                    }
                },
                color: ['#62ACEB', '#FDD158', '#B3D465'],
                series: [
                    {
                        name: legend[0],
                        type: 'line',
                        data: this.month_data.lastYear,
                        smooth: true,
                        symbol: 'circle',
                        lineStyle: {
                            color: '#62ACEB'
                        }
                    },
                    {
                        name: legend[1],
                        type: 'line',
                        data: this.month_data.thisYear,
                        smooth: true,
                        symbol: 'circle',
                        lineStyle: {
                            color: '#FDD158'
                        }
                    },
                    {
                        name: legend[2],
                        type: 'line',
                        data: this.month_data.baseLine,
                        smooth: true,
                        symbol: 'circle',
                        lineStyle: {
                            color: '#B3D465'
                        }
                    }
                ]
            };
        });
    }

    // Statistics(by Incident Type)
    _setTypeOptions() {
        function commonOptions(data, showLegend: boolean, seriesOptions) {
            return {
                legend: {
                    backgroundColor: '#363a70', //背景色
                    show: showLegend,
                    orient: 'vertical',
                    right: 0,
                    textStyle: {
                        color: '#ffffff'
                    }
                    // itemGap: 20,
                    // top: 20,
                    // data: ['Car', 'Bus', 'Truck', 'Others']
                },
                tooltip: {
                    formatter: '{b}: {c} / {d}%'
                },
                color: [
                    '#FDD158',
                    '#238CE6',
                    '#B3D465',
                    '#F39800',
                    '#F5736E',
                    '#6C6CFF',
                    '#71B5F4',
                    '#0e0ec6',
                    '#fdbc0b',
                    '#6d813d',
                    '#825100',
                    '#393995',
                    '#a82722',
                    '#97d700',
                    '#5b1095'
                ],
                series: [
                    {
                        name: 'Incident Type',
                        type: 'pie',
                        radius: ['20%', '45%'],
                        center: ['65%', '45%'],
                        right: 72,
                        data,
                        label: {
                            formatter: params => {
                                if (params.percent >= 5) {
                                    return `${params.percent}%`;
                                } else {
                                    return '';
                                }
                            }
                            // rotate: true
                        },
                        labelLine: {
                            show: false,
                            length: 5,
                            length2: 5
                        },
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        ...seriesOptions
                    }
                ]
            };
        }

        this.type_data_last.forEach(type => {
            this.translate.get('Data_Visualization.IncidentAnalytics.' + type.name).subscribe((res: string) => {
                type.name = res || '';
            });
        });
        this.type_data_this.forEach(type => {
            this.translate.get('Data_Visualization.IncidentAnalytics.' + type.name).subscribe((res: string) => {
                type.name = res || '';
            });
        });
        setTimeout(() => {
            this.type_options_last = commonOptions(this.type_data_last, false, {}) as EChartOption;
            this.type_options_this = commonOptions(this.type_data_this, true, { center: ['30%', '45%'] }) as EChartOption;
        });
    }

    // Statistics(by Incident Reason)
    _setReasonOptions() {
        function commonOptions(data, showLegend: boolean, seriesOptions) {
            return {
                legend: {
                    backgroundColor: '#363a70', //背景色
                    show: showLegend,
                    orient: 'vertical',
                    right: 0,
                    textStyle: {
                        color: '#ffffff'
                    }
                    // top: 'middle',
                    // itemGap: 20,
                },
                tooltip: {
                    formatter: '{b}: {c} / {d}%'
                },
                color: [
                    '#FDD158',
                    '#238CE6',
                    '#B3D465',
                    '#F39800',
                    '#F5736E',
                    '#6C6CFF',
                    '#71B5F4',
                    '#0e0ec6',
                    '#fdbc0b',
                    '#6d813d',
                    '#825100',
                    '#393995',
                    '#a82722',
                    '#97d700',
                    '#5b1095'
                ],
                series: [
                    {
                        name: 'Incident Reason',
                        type: 'pie',
                        radius: ['0', '60%'],
                        center: ['50%', '60%'],
                        data,
                        label: {
                            formatter: params => {
                                if (params.percent >= 5) {
                                    return `${params.percent}%`;
                                } else {
                                    return '';
                                }
                            }
                            // rotate: true
                        },
                        labelLine: {
                            show: false,
                            length: 5,
                            length2: 5
                        },
                        itemStyle: {
                            emphasis: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        ...seriesOptions
                    }
                ]
            };
        }

        this.reason_options_last = commonOptions(this.reason_data_last, false, {}) as EChartOption;
        this.reason_options_this = commonOptions(this.reason_data_this, true, { center: ['35%', '60%'] }) as EChartOption;
    }
}
